#!/bin/bash
#make.list.sh
#according to vm.list.txt file generation vm.tf
#根据vm.list.txt文件生成vm.tf

#vm.tf
cat vm.list.txt |egrep -v "^$|#" | while read line;do
echo "# $line"
[ "$(echo $line |awk -F ',' '{print $7}')" = "" ] && { N7=ubuntu ; } || { N7=$(echo $line |awk -F ',' '{print $7}') ; }
[ "$(echo $line |awk -F ',' '{print $8}')" = "" ] && { N8="Create with terraform $(date +%F)" ; } || { N8="$(echo $line |awk -F ',' '{print $8}')" ; }
cat << EOF
module "$(echo $line |awk -F ',' '{print $1}')" {
    source      = "../modules/kvm"
    name        = "$(echo $line |awk -F ',' '{print $1}')"
    count       = $(echo $line |awk -F ',' '{print $2}')
    cpu_core    = $(echo $line |awk -F ',' '{print $3}')
    memory_gb   = $(echo $line |awk -F ',' '{print $4}')
    disk_gb     = $(echo $line |awk -F ',' '{print $5}')
    vid         = $(echo $line |awk -F ',' '{print $6}')
    os          = "$N7"
    notes       = "$N8"
}

EOF
done >vm.tf


#outputs.tf
L=$(cat vm.list.txt |egrep -v "^$|#" |wc -l)

cat > outputs.tf << EOF
output "ip" {
  value = [
EOF
cat vm.list.txt |egrep -v "^$|#" |awk -F ',' 'NR<'$L'  {print "    \"${module."$1".ip}\","}' >>outputs.tf
cat vm.list.txt |egrep -v "^$|#" |awk -F ',' 'NR=='$L' {print "    \"${module."$1".ip}\""}'  >>outputs.tf
cat >> outputs.tf << EOF
  ]
}
EOF

cat >> outputs.tf << EOF
output "name" {
  value = [
EOF
cat vm.list.txt |egrep -v "^$|#" |awk -F ',' 'NR<'$L'  {print "    \"${module."$1".name}\","}' >>outputs.tf
cat vm.list.txt |egrep -v "^$|#" |awk -F ',' 'NR=='$L' {print "    \"${module."$1".name}\""}'  >>outputs.tf
cat >> outputs.tf << EOF
  ]
}
EOF

cat >> outputs.tf << EOF
output "vid" {
  value = [
EOF
cat vm.list.txt |egrep -v "^$|#" |awk -F ',' 'NR<'$L'  {print "    \"${module."$1".vid}\","}' >>outputs.tf
cat vm.list.txt |egrep -v "^$|#" |awk -F ',' 'NR=='$L' {print "    \"${module."$1".vid}\""}'  >>outputs.tf
cat >> outputs.tf << EOF
  ]
}
EOF

